package ua.at.tsvetkov.samizdat.activities;

import java.util.Calendar;
import ua.at.tsvetkov.application.AppConfig;
import ua.at.tsvetkov.net.NetCheckerHelper;
import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.data.Url;
import ua.at.tsvetkov.samizdat.database.DatabaseHelper;
import ua.at.tsvetkov.samizdat.services.SrvBooks;
import ua.at.tsvetkov.samizdat.services.SrvGenres;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;

public class AcStartScreen extends Activity {

	private ProgressBar	initProgressBar;
	private TextView		initTextView;
	private TextView		timerTextView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_start_screen);

		createAlarmUpdate();

		initProgressBar = (ProgressBar) findViewById(R.id.initProgressBar);
		initTextView = (TextView) findViewById(R.id.ac_start_screen_loading_text_view);
		timerTextView = (TextView) findViewById(R.id.ac_start_screen_timer_text_view);
		initProgressBar.setMax(100);

		IntentFilter intentFilter = new IntentFilter(Const.BROADCAST_MESSAGE);
		registerReceiver(intentReceiver, intentFilter);

		// AppConfig.getLong(Const.LAST_UPDATE_DATE, -1);

		// mConnection = new ServiceConnection() {
		// public void onServiceConnected(ComponentName className, IBinder service) {
		// }
		// public void onServiceDisconnected(ComponentName className) {
		// }
		// };

		// bindService(new Intent(this, SrvGenres.class), mConnection, Context.BIND_AUTO_CREATE);
	}

	private void runDownloadServices() {
		if (NetCheckerHelper.checkNet(this, Url.getBaseUrl()) != false) {
			if (!isDownloadigServicesRunning()) {// run service if it have not already runned
				deleteDatabase(DatabaseHelper.DATABASE_NAME);
				startService(new Intent(this, SrvGenres.class));
			}
		} else {
			showNoNetDialog();
		}
	}

	private void createAlarmUpdate() {
		// AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		// Intent intent = new Intent(this, BrSamizdat.class).putExtra(Const.ALARM_MANAGER_LAUNCH, Const.ALARM_MANAGER_LAUNCH);
		// PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		// // На случай, если мы ранее запускали активити, а потом поменяли время,
		// // откажемся от уведомления
		// am.cancel(pendingIntent);
		// // Устанавливаем разовое напоминание
		// Date date = new Date();
		// date.setHours(24);
		// date.setMinutes(0);
		// date.setSeconds(0);
		// am.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
	}

	private boolean isDownloadigServicesRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		boolean answer = false;
		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			if ("ua.at.tsvetkov.samizdat.services.SrvGenres".equals(service.service.getClassName()) || "ua.at.tsvetkov.samizdat.services.SrvBooks".equals(service.service.getClassName())) {
				answer = true;
			}
		}
		return answer;
	}

	private void showNoNetDialog() {
		AlertDialog.Builder noNetDialog = new AlertDialog.Builder(this);
		noNetDialog.setCancelable(false);
		noNetDialog.setTitle(R.string.NO_CONNECTION);
		// deleteAlert.setMessage(R.string.TURN_ON_WIFI);

		String[] internetTypes = new String[2];
		internetTypes[0] = "WiFi";
		internetTypes[1] = "3G";
		noNetDialog.setItems(internetTypes, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
			}
		});

		noNetDialog.setPositiveButton(this.getString(R.string.RECONNECT), new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				runDownloadServices();
			}
		});
		noNetDialog.setNegativeButton(this.getString(R.string.QUIT), new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				AcStartScreen.this.finish();
			}
		});
		noNetDialog.show();
	}

	private void showDownloadDatabaseDialog() {
		AlertDialog.Builder downloadDatabaseDialog = new AlertDialog.Builder(this);
		downloadDatabaseDialog.setCancelable(false);
		downloadDatabaseDialog.setTitle(R.string.DOWNLOAD_DATABASE);
		downloadDatabaseDialog.setMessage(R.string.DATABASE_SIZE);

		downloadDatabaseDialog.setPositiveButton(this.getString(R.string.DOWNLOAD), new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				runDownloadServices();
			}
		});
		downloadDatabaseDialog.setNegativeButton(this.getString(R.string.QUIT), new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				AcStartScreen.this.finish();
			}
		});
		downloadDatabaseDialog.show();
	}

	BroadcastReceiver	intentReceiver	= new BroadcastReceiver() {
													@Override
													public void onReceive(Context context, Intent intent) {
														Integer percents = intent.getIntExtra(Const.BOOKS_LOADING_PERCENTS, -1);
														Integer secondsLeft = intent.getIntExtra(Const.END_TIME, -1);

														String serviceGenresStarted = intent.getStringExtra(Const.SERVICE_GENRES_STARTED);
														String serviceBooksStarted = intent.getStringExtra(Const.SERVICE_BOOKS_STARTED);

														String serviceBooksStoped = intent.getStringExtra(Const.SERVICE_BOOKS_STOPED);
														String serviceGenresStoped = intent.getStringExtra(Const.SERVICE_GENRES_STOPED);

														String serverIsUnavailable = intent.getStringExtra(Const.SERVER_IS_UNAVAILABLE);

														int sec = (int) (secondsLeft % 60);
														int min = (int) ((secondsLeft / 60) % 60);
														int hr = (int) ((secondsLeft / 3600) % 24);

														String secString = "";
														String minString = "";
														String hrString = "";

														if (sec / 10 <= 0) {
															secString = "0";
															secString = secString.concat(String.valueOf(sec));
														} else {
															secString = secString.concat(String.valueOf(sec));
														}

														if (min / 10 <= 0) {
															minString = "0";
															minString = minString.concat(String.valueOf(min));
														} else {
															minString = minString.concat(String.valueOf(min));
														}

														if (hr / 10 <= 0) {
															hrString = "0";
															hrString = hrString.concat(String.valueOf(hr));
														} else {
															hrString = hrString.concat(String.valueOf(hr));
														}

														if (percents != -1) {
															initProgressBar.setProgress(percents);
															initTextView.setText(getString(R.string.BOOKS_ARE_DOWNLOADING) + " " + getString(R.string.DOWNLOADED) + " " + String.valueOf(percents) + "%");
														}

														if (secondsLeft != -1) {
															timerTextView.setText(getString(R.string.TIME_LEFT) + " " + hrString + ":" + minString + ":" + secString);
														}

														if (serviceGenresStarted != null && serviceGenresStarted.equals(Const.SERVICE_GENRES_STARTED)) {
															initTextView.setText(getString(R.string.GENRES_ARE_DOWNLOADING));
														}
														if (serviceBooksStarted != null && serviceBooksStarted.equals(Const.SERVICE_BOOKS_STARTED)) {
															initTextView.setText(getString(R.string.BOOKS_ARE_DOWNLOADING));
														}
														if (serviceGenresStoped != null && serviceGenresStoped.equals(Const.SERVICE_GENRES_STOPED)) {
															startService(new Intent(AcStartScreen.this, SrvBooks.class));
														}
														if (serviceBooksStoped != null && serviceBooksStoped.equals(Const.SERVICE_BOOKS_STOPED)) {

															AppConfig.putSetting(Const.DATA_BASE_IS_LOADED, Const.DATA_BASE_IS_LOADED, true);
															AppConfig.putSetting(Const.LAST_UPDATE_DATE, Calendar.getInstance().getTimeInMillis(), true);
															if (isTablet(AcStartScreen.this)) {
																Intent startActivity = new Intent(AcStartScreen.this, AcMainTablet.class);
																startActivity(startActivity);
																finish();
															} else {
																Intent startActivity = new Intent(AcStartScreen.this, AcMainPhone.class);
																startActivity(startActivity);
																finish();
															}
														}

														if (serverIsUnavailable != null) {
															AlertDialog.Builder serverUnavailableAlert = new AlertDialog.Builder(AcStartScreen.this);
															serverUnavailableAlert.setTitle("Ошибка загрузки!");
															serverUnavailableAlert.setMessage("В данный момент сервер недоступен.");
															serverUnavailableAlert.setPositiveButton("OK", new OnClickListener() {

																@Override
																public void onClick(DialogInterface dialog, int which) {
																	dialog.cancel();
																	AcStartScreen.this.finish();
																}
															});
															serverUnavailableAlert.show();
														}
													}
												};

	public boolean isTablet(Context context) {
		boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
		// boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
		return (xlarge /* || large */);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(intentReceiver);
	}

	@Override
	protected void onResume() {
		super.onResume();

		String isDBLoaded = AppConfig.getString(Const.DATA_BASE_IS_LOADED);

		if (isDBLoaded != null && isDBLoaded.equals("")) {// in this case DB is NOT loaded, and net is enable
			if (!isDownloadigServicesRunning()) {
				showDownloadDatabaseDialog();
			}
		} else {
			if (isTablet(AcStartScreen.this)) {
				Intent startActivity = new Intent(AcStartScreen.this, AcMainTablet.class);
				startActivity(startActivity);
				finish();
			} else {
				Intent startActivity = new Intent(AcStartScreen.this, AcMainPhone.class);
				startActivity(startActivity);
				finish();
			}
		}
	}

}
